import { createStore } from 'vuex'
import {set,get} from '@/utils/localStorage'

export default createStore({
  state: {
    /* {shopId:{productId:{,...,count,check,}}} */
    cartList: get('cartList')
  },
  getters: {
  },
  mutations: {
    // 购物车添加
    add: (state, {product,shopId}) => {
      const productList = state.cartList[shopId];
      if(!productList){
        product.check = true
        product.count = 1;
        state.cartList[shopId] = {[product._id]:product}; 
      }else{
        if (Object.keys(productList).includes(product._id)) productList[product._id].count++
        else {
          product.count = 1
          product.check = true
          productList[product._id] = product
        }
      }
      set('cartList',state.cartList);
    },
    // 购物车减少
    sub:(state,{product,shopId}) => {
      const productList = state.cartList[shopId];
      if(--productList[product._id].count === 0) delete productList[product._id]
      set('cartList',state.cartList);
    } ,
    // 勾选
    check:(state,{shopId,productId}) => {
      state.cartList[shopId][productId].check = !state.cartList[shopId][productId].check
      set('cartList',state.cartList);
    },
    // 勾选全部
    checkAll:(state,{shopId,status}) => {
      const productList = state.cartList[shopId];
      for(const item in productList) productList[item].check = status
      set('cartList',state.cartList);
    },
    // 清空
    clear:(state,shopId) => {
      const productList = state.cartList[shopId];
      for(const item in productList) {
        productList[item].count = null;
        delete productList[item]
      }
      set('cartList',state.cartList);
    } 
  },
  actions: {
  },
  modules: {
  }
})
